package com.xwaf.platform.web.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import com.xwaf.platform.common.api.constants.RedisKeys;
import com.xwaf.platform.common.api.entity.TokenInfo;
import com.xwaf.platform.common.api.exception.BusinessRunTimeException;
import com.xwaf.platform.common.redis.util.RedisUtil;
import com.xwaf.platform.common.web.util.Response;

@Order(1)
@WebFilter(urlPatterns = "/m/*", filterName = "loginFilter")
public class LoginFilter implements Filter {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	private static final Set<String> ALLOWED_PATHS = Collections
			.unmodifiableSet(new HashSet<>(Arrays.asList("/m/login", "/m/code")));

	@Autowired
	private RedisUtil redisUtil;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException, BusinessRunTimeException {
		HttpServletRequest reqes = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String path = reqes.getRequestURI().substring(reqes.getContextPath().length()).replaceAll("[/]+$", "");
		boolean allowedPath = ALLOWED_PATHS.contains(path);
		if (allowedPath) {
			logger.info("不需要处理的url进入的方法");
			chain.doFilter(reqes, resp);
		} else {
			String token = reqes.getHeader("token");
			boolean flag = true;
			if (!StringUtils.isNotBlank(token)) {
				Response.writeJson(resp, 3, "未登录，请登录");
				flag = false;
			}
			if (flag) {
				TokenInfo tokenInfo = (TokenInfo) redisUtil.get(RedisKeys.TOKEN_INFO + token);
				if (tokenInfo == null) {
					Response.writeJson(resp, 3, "登录过期! 请重新登录");
				} else {
					chain.doFilter(reqes, resp);
				}
			}
		}
	}

	@Override
	public void destroy() {

	}

}
